package cn.xiongxf.web.controller;

import cn.xiongxf.dto.UserRegisterDto;
import cn.xiongxf.service.IUserService;
import cn.xiongxf.domain.User;
import cn.xiongxf.query.UserQuery;
import cn.xiongxf.result.JsonResult;
import cn.xiongxf.result.PageList;
import cn.xiongxf.vo.RecommendCodeVO;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public IUserService userService;

    /**
    * 带条件分页查询数据
    */
    @RequestMapping(value = "/pagelist",method = RequestMethod.POST)
    public JsonResult page(@RequestBody UserQuery query){
        Page<User> page = new Page<User>(query.getPage(),query.getRows());
        page = userService.selectPage(page);
        return JsonResult.success(new PageList<User>(page.getTotal(),page.getRecords()));
    }

    /**
    * 查询所有对象
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public JsonResult list(){
        return JsonResult.success(userService.selectList(null));
    }


    /**
   * 查询单个对象
   */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.success(userService.selectById(id));
    }

    /**
    * 删除对象
    */
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public JsonResult delete(@PathVariable("id") Long id){
            userService.deleteById(id);
        return JsonResult.success();
    }

    /**
    * 保存/修改对象
    */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public JsonResult saveOrUpdate(@RequestBody User user){
        if(user.getId()!=null){
            userService.updateById(user);
        }else{
            userService.insert(user);
        }
        return JsonResult.success();
    }

    /**
     * 用户手机短信注册
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public JsonResult register(@RequestBody @Valid UserRegisterDto userRegisterDto){
        userService.register(userRegisterDto);
        return JsonResult.success();
    }

    /**
     * 根据用户ID生成推存码及二维码并保存到DB
     */
    @RequestMapping(value = "/recommendCodeForUser/{userId}", method = RequestMethod.GET)
    public JsonResult register(@PathVariable Long userId){
        RecommendCodeVO recommendCodeVO = userService.recommendCodeForUser(userId);
        return JsonResult.success(recommendCodeVO);
    }

}
